﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using System.Collections.Generic;
using System.IO;
using TomNet.Core.Options;

namespace TomNet.AspNetCore.Mvc
{
    public static class UploadApplicationBuilderExtensions
    {
        private static void UseFileUploadOptions(IApplicationBuilder app, UploadOptions options)
        {
            if (!Directory.Exists(options.UploadPath))
            {
                Directory.CreateDirectory(options.UploadPath);
            }

            app.UseStaticFiles(new StaticFileOptions()
            {
                RequestPath = options.RequestPath,
                FileProvider = new PhysicalFileProvider(options.UploadPath)
            });
        }

        public static IApplicationBuilder UseUploadOptions(this IApplicationBuilder app)
        {
            var _options = app.ApplicationServices.GetTomNetOptions();
            foreach (KeyValuePair<string, UploadOptions> pair in _options.UploadPolicies)
            {
                UseFileUploadOptions(app, pair.Value);
            }
            return app;
        }
    }
}
